package com.hzx.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.hzx.entity.Dept;
import com.hzx.entity.Emp;
import com.hzx.service.EmpService;

@Controller
@Scope("prototype")
public class EmpAction extends BaseAction<Emp> {
	@Autowired
	private EmpService empService;

	public String add() {
		empService.save(model);
		return LIST;
	}

	// 显示未离职的员工 分页
	public String findByPage() throws IOException {
		DetachedCriteria criteria = pageBean.getCriteria();
		// 添加条件
		criteria.add(Restrictions.eq("eis", model.getEis()));
		empService.pageQuery(pageBean);
		// java转json
		objToJson(pageBean, new String[] { "currentPage", "pageSize", "criteria", "emps" });
		return NONE;
	}

	// 显示所有员工 分页
	public String pageQuery() throws IOException {
		empService.pageQuery(pageBean);
		// java转json
		objToJson(pageBean, new String[] { "currentPage", "pageSize", "criteria", "emps" });
		return NONE;
	}
	public String empQuery() throws IOException{
		String empname = model.getEname();
		DetachedCriteria criteria = pageBean.getCriteria();
		//根据员工姓名查询
		if (StringUtils.isNotBlank(empname)) {
			criteria.add(Restrictions.like("ename", "%" + empname + "%"));
		}
		empService.pageQuery(pageBean);
		// java转json
		objToJson(pageBean, new String[] {"currentPage", "pageSize", "criteria", "emps" });
		return NONE;
	}
	public String deptQuery() throws IOException{
		DetachedCriteria criteria = pageBean.getCriteria();
		Integer deptid =model.getDept().getDid();
		// 部门
		if(deptid != null){
			// 别名
			System.out.println(deptid);
			if(deptid == -1){
				//未选择部门  选择部门为空的
				criteria.add(Restrictions.eq("eis",0 ));
			}else{
				criteria.add(Restrictions.eq("dept.did",deptid ));
			}
		}
		empService.pageQuery(pageBean);
		// java转json
		objToJson(pageBean, new String[] {"currentPage", "pageSize", "criteria", "emps" });
		return NONE;
	}
	public String findByid() {
		Emp emp = empService.findByid(model.getEid());
		session.put("emp", emp);
		return UPDATE;
	}

	public String addOrupdate() {
		empService.saveOrupdate(model);
		return NONE;
	}

	// 离职员工
	public String deleteEmp() throws IOException {
		empService.deleteEmp(model.getEid());
		writeJsp("success");
		objToJson(pageBean);
		return NONE;
	}

	// 恢复员工
	public String restoreEmp() {
		session.remove("emp");
		empService.restoreEmp(model);
		return NONE;
	}

	public String findEmp() {
		Emp emp = empService.findByid(model.getEid());
		session.put("emp", emp);
		return RESTORE;
	}
	
	public String findAll() throws IOException{
		List<Emp> list =empService.findAll();
		listToJson(list, new String[] {"currentPage", "pageSize", "criteria", "emps"});
		return NONE;
		
	}

}
